import os
import time
import requests
import subprocess

def getDir(path):
    """获取文件目录"""
    if path == None or len(path) == 0:
        return
    dir = os.path.dirname(path)
    return dir


def mkdir(path):
    """创建目录"""
    if path == None or len(path) == 0:
        return
    path = path.strip()
    path = path.rstrip("\\")
    isExists = os.path.exists(path)
    if not isExists:
        os.makedirs(path)

# requests下载
def download(url, dir, name):
    """
    下载文件
    :param url:文件地址
    :param dir:目录
    :param name:文件名
    """
    mkdir(dir)
    if name == None or len(name) == 0:
        name = url.split('/')[-1]

    print(name)

    r = requests.get(url, stream=True)
    with open(dir + '/' + name, 'wb') as file:
        # 请求文件的大小单位字节B
        total_size = int(r.headers['content-length'])
        # 以下载的字节大小
        content_size = 0
        # 进度下载完成的百分比
        plan = 0
        # 请求开始的时间
        start_time = time.time()
        # 上秒的下载大小
        temp_size = 0

        for chunk in r.iter_content(chunk_size=1024 * 1024):
            if chunk:
                file.write(chunk)
                # 统计以下载大小
                content_size += len(chunk)
                # 计算下载进度
                plan = round((content_size / total_size) * 100)
                # 每一秒统计一次下载量
                if time.time() - start_time > 1:
                    # 重置开始时间
                    start_time = time.time()
                    # 每秒的下载量
                    speed = content_size - temp_size
                    # KB级下载速度处理
                    if 0 <= speed < (1024 ** 2):
                        print(plan, '  ', speed / 1024, 'KB/s')
                    # MB级下载速度处理
                    elif (1024 ** 2) <= speed < (1024 ** 3):
                        print(plan, '  ', speed / (1024 ** 2), 'MB/s')
                    # GB级下载速度处理
                    elif (1024 ** 3) <= speed < (1024 ** 4):
                        print(plan, '  ', speed / (1024 ** 3), 'GB/s')
                    # TB级下载速度处理
                    else:
                        print(plan, '  ', speed / (1024 ** 4), 'TB/s')
                    # 重置以下载大小
                    temp_size = content_size

    print("%s 下载完成!\n" % name)
    return name

# you-get下载
def get_download(url, dir):
    command = 'you-get'
    if len(dir) > 0:
        command = command + " -o " + dir
    command = command + " " + url

    print(command)

    # reply = subprocess.getoutput(command)
    reply = subprocess.check_output(command)
    return reply.decode('utf-8')

# 终端执行命令
def terminal(command):
    if command == None:
        return "执行命令为空"
    print(command)
    reply = subprocess.check_output(command)
    # return reply.decode('utf-8')

    return subprocess_check_output(command)


def subprocess_check_output(*args):
    p = subprocess.Popen(*args, shell=True, stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    msg = ''
    for line in p.stdout.readlines():
        msg += line.decode()
    status = p.wait()
    return msg

